import { HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class LoginInfoService {
  public isLoggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
  // public userInfo = new BehaviorSubject<UserInfoDto>(new UserInfoDto());

  public loggedInEvent = new BehaviorSubject<boolean>(false);

  constructor(private _cookieService: CookieService) 
  { 
    this.isLoggedIn.next(false);
  }

  getToken(): string | undefined {
    if (this._cookieService.check('access_token')) {
      return this._cookieService.get('access_token');
    } else {
      return undefined;
    }
  }

  headers(): HttpHeaders {
    const token = this.getToken();
    const headers = new HttpHeaders();
    let result = headers;
    if (token != null) {
      result = headers.append("Authorization", 'Bearer ' + token);
    } 
     
    if (token != undefined) {
      // console.log(`headers with token ${token}`);
      if (headers.has('Authorization')) {
        console.log('has Authorization');
      } else {
        console.log('has no Authorization');
      }
      console.log('print header keys1');
      for (const key in headers.keys()) {
        console.log(`key ${key}`);
      }
    } else {
      console.log(`no headers`);
    }

    console.log('print header keys');
    for (const key in headers.keys()) {
      console.log(`key ${key}`);
    }
    return result;
  } 
}
